$(function() {
    echart_3();
    //获得url 的参数
    function getQueryString(str) {
        var url = window.location.href;

        var obj = {};
        var reg = /\?/;
        if (url.match(reg)) {
            //判断传入参数，以问号截取，问号后是参数
            var chars = url.split('?')[1];

            //再截&号
            var arr = chars.split('&');

            //获得截取后的数组为键值对字符串
            for (var i = 0; i < arr.length; i++) {

                //保守一点确定看是否为 name=value形式
                var num = arr[i].indexOf("=");

                if (num > 0) {
                    //拼接字符串
                    var name = arr[i].substring(0, num);
                    var value = arr[i].substr(num + 1);

                    //拼接对象，并转码
                    obj[decodeURIComponent(name)] = decodeURIComponent(value);
                }
            }
        }
        return obj[str];
    }

    var n = getQueryString("areaname");
    var aid = getQueryString("aid");

    $("#t1").html(n);
    $("#t2").html(n);
    $("#t3").html(n);
    $("#t4").html(n);
    //重点医院
    $.ajax({
        url: "../../../Message/hospCollect",
        dataType: "json",
        type: "post",
        success: function(res) {
            var j = res.data;
            var str = '';
            var l = j.length > 4 ? 4 : j.length;
            for (var i = 0; i < l; i++) {
                var k = j[i][7];
                str += "<div>";
                str += "<img src='../../layuiadmin/layui/images/hospital/yy" + j[i][8] + ".jpg' alt=''></img>";
                if (k.length > 10) {
                    var c = Math.ceil(k.length / 2);
                    str += "<h3>" + k.substring(0, c) + "</br>" + k.substring(c) + "</h3>";
                } else {
                    str += "<h3>" + j[i][7] + "</h3>";
                }
                str += "</div>"
            }
            $("#hosp").prepend(str);
            echart_1(is0ornot(j[0][0]), is0ornot(j[0][1]), is0ornot(j[0][2]), is0ornot(j[0][3]), is0ornot(j[0][4]), is0ornot(j[0][5]));
            layui.use('carousel', function() {
                var carousel = layui.carousel;
                //建造实例
                carousel.render({
                    elem: '#test1',
                    width: '90%' //设置容器宽度
                        ,
                    arrow: 'hover' //始终显示箭头
                        //,anim: 'updown' //切换动画方式
                        ,
                    indicator: "none",
                    interval: 30000,
                    autoplay: true,
                    height: '3.6rem'
                });
                carousel.on('change(test1)', function(obj) { //test1来源于对应HTML容器的 lay-filter="test1" 属性值
                    var index = obj.index;
                    var a1 = parseFloat(j[index][0]); //grx
                    var a2 = parseFloat(j[index][1]); //ssx
                    var a3 = parseFloat(j[index][2]); //hxx
                    var a4 = parseFloat(j[index][3]); //ywx
                    var a5 = parseFloat(j[index][4]); //blx
                    var a6 = (parseFloat(j[index][5]) + parseFloat(j[index][6])); //syp syd

                    echart_1(a1, a2, a3, a4, a5, a6);
                });
            });
        }
    })

    function is0ornot(num) {
        if (parseFloat(num) == 0 || parseFloat(num) == 0.0) {
            return 0
        } else {
            return parseFloat(num).toFixed(2);
        }
    }

    function echart_1(a1, a2, a3, a4, a5, a6) {
        // 基于准备好的dom，初始化echarts实例
        a1 = is0ornot(a1);
        a2 = is0ornot(a2);
        a3 = is0ornot(a3);
        a4 = is0ornot(a4);
        a5 = is0ornot(a5);
        a6 = is0ornot(a6);
        var myChart = echarts.init(document.getElementById('chart_1'));
        option = {
            color: ['#CD4F62', '#E08F18', '#5CA8BB', '#5D9D1D', '#704FCB', '#707474'],
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c} 公斤({d}%)",

            },
            legend: {
                top: '80%',
                data: ['感染性', '损伤性', '药物性', '病理性', '化学性', '其他'],
                textStyle: {
                    color: '#fff'
                }
            },
            series: [

                {
                    name: '收集量',
                    type: 'pie',
                    radius: ['40%', '55%'],
                    label: {
                        normal: {
                            formatter: '{b|{b}}\n {c}',
                            borderRadius: 4,
                            rich: {
                                b: {
                                    fontSize: 12
                                },
                            }
                        }
                    },
                    data: [
                        { value: a1, name: '感染性' },
                        { value: a2, name: '损伤性' },
                        { value: a4, name: '药物性' },
                        { value: a5, name: '病理性' },
                        { value: a3, name: '化学性' },
                        { value: a6, name: '其他' }
                    ]
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    }
    $.ajax({
        url: "../../../Message/monthCollect",
        dataType: "json",
        type: "post",
        success: function(res) {
            var data = res.data;
            var month = [];
            var values = [];
            for (var i = 0; i < data.length; i++) {
                for (x in data[i]) {
                    var a = x.split("-");
                    month[i] = a[1] + "月";
                    if (data[i][x] == "" || data[i][x] == null) {
                        values[i] = 0
                    } else {
                        values[i] = parseFloat(data[i][x]).toFixed(2)
                    }
                }
            }
            echart_2(month, values)
        }
    })

    function echart_2(month, values) {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById('chart_2'));
        var data = {
            id: 'multipleBarsLines',

            xAxis: month,
            yAxis: [
                values
            ],
            lines: [
                values
            ],
            // xAxis: ['7月', '8月', '9月', '10月', '11月', '12月'],
            // yAxis: [
            //     [15, 10, 14, 11, 7, 16]
            // ],
            // lines: [
            //     [15, 10, 14, 11, 7, 16]
            // ],
            barColor: ['#3FA7DC', '#7091C4', '#5170A2'], //柱子颜色 必填参数
            lineColor: ['#D9523F'], // 折线颜色

        };
        /////////////end/////////

        var myData = (function test() {
            var yAxis = data.yAxis || [];
            var lines = data.lines || [];
            var legendBar = data.legendBar || [];
            var legendLine = data.legendLine || [];
            var symbol = data.symbol || ' ';
            var seriesArr = [];
            var legendArr = [];
            yAxis && yAxis.forEach((item, index) => {
                legendArr.push({
                    name: legendBar && legendBar.length > 0 && legendBar[index]
                });
                seriesArr.push({
                    name: legendBar && legendBar.length > 0 && legendBar[index],
                    type: 'bar',
                    barGap: '0.5px',
                    data: item,
                    barWidth: data.barWidth || 12,
                    label: {
                        normal: {
                            show: true,
                            formatter: '{c}',
                            position: 'top',
                            textStyle: {
                                color: '#fff',
                                fontStyle: 'normal',
                                textAlign: 'left',
                                fontSize: 13,
                            },
                        },
                    },
                    itemStyle: { //图形样式
                        normal: {
                            barBorderRadius: 4,
                            color: data.barColor[index]
                        },
                    }
                });
            });

            lines && lines.forEach((item, index) => {
                legendArr.push({
                    name: legendLine && legendLine.length > 0 && legendLine[index]
                })
                seriesArr.push({
                    name: legendLine && legendLine.length > 0 && legendLine[index],
                    type: 'line',
                    data: item,
                    itemStyle: {
                        normal: {
                            color: data.lineColor[index],
                            lineStyle: {
                                width: 3,
                                type: 'solid',
                            }
                        }
                    },
                    label: {
                        normal: {
                            show: false, //折线上方label控制显示隐藏
                            position: 'top',
                        }
                    },
                    symbol: 'circle',
                    symbolSize: 10
                });
            });

            return {
                seriesArr,
                legendArr
            };
        })();


        option = {
                title: {
                    show: true,
                    top: '10%',
                    left: '3%',
                    text: data.title,
                    textStyle: {
                        fontSize: 18,
                        color: '#fff'
                    },
                    subtext: data.subTitle,
                    link: ''
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        var time = '';
                        var str = '';
                        for (var i of params) {
                            time = i.name.replace(/\n/g, '') + '<br/>';
                            if (i.data == 'null' || i.data == null) {
                                str += i.seriesName + '：无数据' + '<br/>';
                                break;
                            } else {
                                str += '收集量：' + i.data + '公斤<br/>';
                                break;
                            }

                        }
                        return time + str;
                    },
                    axisPointer: {
                        type: 'none'
                    },
                },
                legend: {
                    right: data.legendRight || '30%',
                    top: '12%',
                    right: '5%',
                    itemGap: 16,
                    itemWidth: 10,
                    itemHeight: 10,
                    data: myData.legendArr,
                    textStyle: {
                        color: '#fff',
                        fontStyle: 'normal',
                        fontFamily: '微软雅黑',
                        fontSize: 12,
                    }
                },
                grid: {
                    x: 30,
                    y: 80,
                    x2: 30,
                    y2: 60,
                },
                xAxis: {
                    type: 'category',
                    data: data.xAxis,
                    axisTick: {
                        show: false,
                    },

                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#1AA1FD',
                        },
                        symbol: ['none', 'arrow']
                    },
                    axisLabel: {
                        show: true,
                        interval: '0',
                        textStyle: {
                            lineHeight: 16,
                            padding: [2, 2, 0, 2],
                            height: 50,
                            fontSize: 12,
                        },
                        rich: {
                            Sunny: {
                                height: 50,
                                // width: 60,
                                padding: [0, 5, 0, 5],
                                align: 'center',
                            },
                        },
                        formatter: function(params, index) {
                            var newParamsName = "";
                            var splitNumber = 5;
                            var paramsNameNumber = params && params.length;
                            if (paramsNameNumber && paramsNameNumber <= 4) {
                                splitNumber = 4;
                            } else if (paramsNameNumber >= 5 && paramsNameNumber <= 7) {
                                splitNumber = 4;
                            } else if (paramsNameNumber >= 8 && paramsNameNumber <= 9) {
                                splitNumber = 5;
                            } else if (paramsNameNumber >= 10 && paramsNameNumber <= 14) {
                                splitNumber = 5;
                            } else {
                                params = params && params.slice(0, 15);
                            }

                            var provideNumber = splitNumber; //一行显示几个字
                            var rowNumber = Math.ceil(paramsNameNumber / provideNumber) || 0;
                            if (paramsNameNumber > provideNumber) {
                                for (var p = 0; p < rowNumber; p++) {
                                    var tempStr = "";
                                    var start = p * provideNumber;
                                    var end = start + provideNumber;
                                    if (p == rowNumber - 1) {
                                        tempStr = params.substring(start, paramsNameNumber);
                                    } else {
                                        tempStr = params.substring(start, end) + "\n";
                                    }
                                    newParamsName += tempStr;
                                }

                            } else {
                                newParamsName = params;
                            }
                            params = newParamsName;
                            return '{Sunny|' + params + '}';
                        },
                        color: '#1AA1FD',
                    },

                },
                yAxis: {
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: '#1AA1FD',
                        },
                        symbol: ['none', 'arrow']
                    },
                    type: 'value',
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        show: false
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: '#1AA1FD',
                            type: 'solid'
                        },
                    }
                },
                series: myData.seriesArr
            }
            // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    }



    function echart_3() {
        // 基于准备好的dom，初始化echarts实例
        var colors = [
            "#1e9fff", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00",
            "#b82e2e", "#316395", "#994499", "#22aa99", "#aaaa11", "#6633cc", "#e67300", "#8b0707",
            "#651067", "#329262", "#5574a6", "#3b3eac"
        ];
        var myChart = echarts.init(document.getElementById('chart_3'));
        var marker;
        var infoWindow;
        var content;
        var i = 0;

        function showProvince() {
            $.ajax({
                url: "../../../Message/regionDayHosp",
                dataType: "json",
                type: "post",
                success: function(res) {
                    var data = res.data;

                    var district, map = new AMap.Map('chart_3', {
                        cursor: 'default',
                        zoom: 12,
                        mapStyle: 'amap://styles/9ab4483922efff6b2894220cadf30946'
                    });
                    //just some colors
                    addHangZhou(n);
                    marker = new AMap.Marker({
                        position: data[0].LngLat.split(","),
                        label: data[0].name
                    });
                    marker.setLabel({ //label默认蓝框白底左上角显示，样式className为：amap-marker-label
                        offset: new AMap.Pixel(20, 20), //修改label相对于maker的位置
                        content: data[0].name
                    });

                    content = "";
                    content = "<div class='map_f'>" + data[0].name + "收集数据：";
                    content += "<div>感染性：" + is0ornot(data[0][0]) + "&nbsp;&nbsp;&nbsp;&nbsp;"
                    content += "损伤性：" + is0ornot(data[0][1]) + "</div>"
                    content += "<div>药物性：" + is0ornot(data[0][3]) + " &nbsp;&nbsp;&nbsp;&nbsp;"
                    content += "病理性：" + is0ornot(data[0][4]) + "</div>"
                    content += "<div>化学性：" + is0ornot(data[0][2]) + "&nbsp;&nbsp;&nbsp;&nbsp;"
                    content += "其他：" + is0ornot(parseFloat(data[0][5]) + parseFloat(data[0][6])) + "</div>"
                    content += "</div>"
                    marker.content = content;
                    infoWindow = new AMap.InfoWindow({
                        offset: new AMap.Pixel(0, 0),
                        autoMove: true
                    });
                    marker.on('click', markerClick);

                    function markerClick(e) {
                        infoWindow.setContent(e.target.content);
                        infoWindow.open(map, e.target.getPosition());
                    }
                    infoWindow.setContent(content);
                    infoWindow.open(map, marker.getPosition());
                    map.add(marker);


                    setInterval(function() {
                        map.remove(marker);
                        infoWindow.close();
                        if (i < data.length - 1) {
                            i++
                        } else {
                            i = 0;
                        }
                        marker = new AMap.Marker({
                            position: data[i].LngLat.split(","),
                        });
                        marker.setLabel({ //label默认蓝框白底左上角显示，样式className为：amap-marker-label
                            offset: new AMap.Pixel(20, 20), //修改label相对于maker的位置
                            content: data[i].name
                        });
                        content = "";
                        content = "<div class='map_f'>" + data[i].name + "收集数据：";
                        content += "<div>感染性：" + is0ornot(data[i][0]) + "&nbsp;&nbsp;&nbsp;&nbsp;"
                        content += "损伤性：" + is0ornot(data[i][1]) + "</div>"
                        content += "<div>药物性：" + is0ornot(data[i][3]) + "&nbsp;&nbsp;&nbsp;&nbsp;"
                        content += "病理性：" + is0ornot(data[i][4]) + "</div>"
                        content += "<div>化学性：" + is0ornot(data[i][2]) + "&nbsp;&nbsp;&nbsp;&nbsp;"
                        content += "其他：" + is0ornot(parseFloat(data[i][5]) + parseFloat(data[i][6])) + "</div>"
                        content += "</div>"
                        marker.content = content;
                        infoWindow = new AMap.InfoWindow({
                            offset: new AMap.Pixel(0, 0)
                        });
                        marker.on('click', markerClick);
                        infoWindow.setContent(content);
                        infoWindow.open(map, marker.getPosition());
                        map.add(marker);


                    }, 30000)

                    function addHangZhou(area) {
                        //加载行政区划插件
                        AMap.service('AMap.DistrictSearch', function() {
                            var opts = {
                                subdistrict: 1, //返回下一级行政区
                                extensions: 'all', //返回行政区边界坐标组等具体信息
                                level: 'city' //查询行政级别为 市
                            };
                            AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
                                    map.addControl(new AMap.ToolBar());
                                    map.addControl(new AMap.Scale());
                                })
                                //实例化DistrictSearch
                            district = new AMap.DistrictSearch(opts);
                            district.setLevel('district');
                            //行政区查询
                            district.search(area, function(status, result) {
                                var bounds = result.districtList[0].boundaries;
                                var polygons = [];
                                if (bounds) {
                                    for (var i = 0, l = bounds.length; i < l; i++) {
                                        //生成行政区划polygon
                                        var polygon = new AMap.Polygon({
                                            map: map,
                                            strokeWeight: 1,
                                            path: bounds[i],
                                            fillOpacity: 0.7,
                                            fillColor: '#2768c3', //填充颜色
                                            strokeColor: '#CC66CC'
                                        });
                                        polygons.push(polygon);
                                    }
                                    map.setFitView(); //地图自适应

                                }
                            });


                        });
                    }

                    var z = ["aa", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
                    var str = "";
                    var x = 0;
                    x = data.length;
                    var newData = group(res.data, 8);
                    for (var k = 0; k < newData.length; k++) {
                        str += "<div>";
                        str += '<main class="t_b_m">';
                        str += ' <div class="t_b_box0"><span>感染性</span></div>';
                        str += ' <div class="t_b_box01"><span>损伤性</span></div>';
                        str += ' <div class="t_b_box02"><span>药物性</span></div>';
                        str += ' <div class="t_b_box03"><span>病理性</span></div>';
                        str += ' <div class="t_b_box04"><span>化学性</span></div>';
                        str += ' <div class="t_b_box05"><span>其他</span></div>';
                        str += "</main>"
                        for (var j = 0; j < newData[k].length; j++, x++) {
                            var nn = newData[k][j].name;
                            if (nn.length > 10) {
                                str += '<header class="t_b_h1" id="' + z[j] + '0"><span>' + nn.substring(0, 10) + '</br>' + nn.substring(10) + '</span></header>';
                            } else {
                                str += '<header class="t_b_h1" id="' + z[j] + '0"><span>' + newData[k][j].name + '</span></header>';
                            }
                            str += '<main class="t_b_m">';
                            str += '<div class="t_b_box" id="' + z[j] + '1"><h2>' + is0ornot(newData[k][j][0]) + '</h2></div>';
                            str += '<div class="t_b_box1" id="' + z[j] + '2"><h2>' + is0ornot(newData[k][j][1]) + '</h2></div>';
                            str += '<div class="t_b_box2" id="' + z[j] + '3"><h2>' + is0ornot(newData[k][j][3]) + '</h2></div>';
                            str += '<div class="t_b_box3" id="' + z[j] + '4"><h2>' + is0ornot(newData[k][j][4]) + '</h2></div>';
                            str += '<div class="t_b_box4" id="' + z[j] + '5"><h2>' + is0ornot(newData[k][j][2]) + '</h2></div>';
                            str += '<div class="t_b_box5" id="' + z[j] + '6"><h2>' + is0ornot(parseFloat(newData[k][j][5]) + parseFloat(newData[k][j][6])) + '</h2></div>';
                            str += '</main>';
                        }
                        str += "</div>";
                    }

                    $("#region").append(str);
                    layui.use('carousel', function() {
                        var carousel = layui.carousel;
                        //建造实例
                        carousel.render({
                            elem: '#test2',
                            width: '100%' //设置容器宽度
                                ,
                            arrow: 'hover' //始终显示箭头
                                //,anim: 'updown' //切换动画方式
                                ,
                            indicator: "none",
                            interval: 30000,
                            autoplay: false,
                            height: '4.6rem'
                        });
                    });
                }
            })
        }
        showProvince();

        function group(array, subGroupLength) {
            let index = 0;
            let newArray = [];
            while (index < array.length) {
                newArray.push(array.slice(index, index += subGroupLength));
            }
            return newArray;
        }
        // 使用刚指定的配置项和数据显示图表。
        // myChart.setOption(option);
        window.addEventListener("resize", function() {
            myChart.resize();
        });
    }

})